<?php

namespace App\Http\Controllers\Counter;

use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Counter\TableAlertAddMinutesRequest;
use App\Http\Requests\Counter\TableAlertSetDateRequest;
use App\Http\Resources\Counter\TableAlertResource;
use App\Http\Resources\TableAlterLogResource;
use App\Models\Table;
use App\Models\TableAlterLog;
use Illuminate\Http\Request;

class TableAlertController extends Controller
{
    public function addMinutes(Table $table, TableAlertAddMinutesRequest $request)
    {
        $minutes = $request->minutes;
        if ($table->alert_date < now()) {
            $table->alert_date = now()->addMinutes($minutes);
        } else {
            $table->alert_date = $table->alert_date->addMinutes($minutes);
        }
        $table->alert_marked = false;
        $table->save();

        TableAlterLog::create([
            'table_id' => $table->id,
            'alert_date' => $table->alert_date,
            'user_id' => auth()->id(),
        ]);

        return ApiResponseHelper::json([]);
    }

    public function setAlertDate(Table $table, TableAlertSetDateRequest $request)
    {
        $hour = $request->hour;
        $minute = $request->minute;

        //判断当前小时是否大于hour, 大于则日期为明天
        if (now()->hour > $hour) {
            $table->alert_date = now()->addDay()->setHour($hour)->setMinute($minute)->setSecond(0);
        } else {
            $table->alert_date = now()->setHour($hour)->setMinute($minute)->setSecond(0);
        }
        $table->alert_marked = false;
        $table->save();

        TableAlterLog::create([
            'table_id' => $table->id,
            'alert_date' => $table->alert_date,
            'user_id' => auth()->id(),
        ]);

        return ApiResponseHelper::json([]);
    }

    public function getExpiredAlertTables()
    {
        $tables = Table::where('alert_date', '<', now())->with([
            'tableType',
        ])->where('alert_marked', false)->get();

        //更新Mark
        $tables->each(function ($table) {
            $table->alert_marked = true;
            $table->save();
        });

        return TableAlertResource::collection($tables);
    }

    public function getPassedAlertTables()
    {
        $logs = TableAlterLog::where('alert_date', '<', now())->with([
            'table',
            'table.tableType',
            'user',
        ])->paginate();

        return TableAlterLogResource::collection($logs);
    }

    public function cancel(Table $table)
    {
        $table->alert_date = null;
        $table->alert_marked = true;
        $table->save();

        return ApiResponseHelper::json([]);
    }
}
